#include	"unp.h"
#include "var.h"

int connectFTPServ(int portN) {

	int n;
	int sockfd;
	struct sockaddr_in servaddr;
	struct sockaddr *name;
	int *namelen;
	char buf[MAXLINE];
	char msg[MAXLINE];

	memset(&buf, 0x00, sizeof(buf));
	fprintf(stderr, "IPNUM:");
	n = Read(0, buf, MAXLINE);

	snprintf(SERVIPADDR, MAXLINE, "%s", buf);

	//sockfd = Socket(AF_INET, SOCK_STREAM, 0);
	sockfd = Socket(PF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));

	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = inet_addr(buf);
	servaddr.sin_port = htons(atoi("21"));

	if (connect(sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr)) == -1) {
		error(1, errno, "Socket Connection error");
		return -1;
	}

	return sockfd;

}

int connectFTPDataServ(int portN) {

	if (ACTIVE_MODE == OFF) {
		int n;
		int sockfd;
		struct sockaddr_in servaddr;

		sockfd = Socket(PF_INET, SOCK_STREAM, 0);

		bzero(&servaddr, sizeof(servaddr));

		servaddr.sin_family = AF_INET;
		servaddr.sin_addr.s_addr = inet_addr(SERVIPADDR);
		servaddr.sin_port = htons(atoi(DATA_PORT_NUM));
		fprintf(stderr, "PORT _NUM %d\n", I_DATA_PORT_NUM);
		fprintf(stderr, "IP   _NUM %s\n", SERVIPADDR);

		if (connect(sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr))== -1) {
			error(1, errno, "Socket Connection error");
			return -1;
		}

		return sockfd;

	} else if (ACTIVE_MODE == ON) {
		return listenFTPServConn();
	}

	return -1;

}

void execCommand(int sockfd, int requestNum,char *command) {

	char buf[MAXLINE];
	int n;
	if(requestNum == OPEN) {
		n = Read(0, buf, MAXLINE);
		snprintf(command, MAXLINE, "USER %s\r\n", buf);
	}
	else if(requestNum == PASSWORD) {
		n = Read(0, buf, MAXLINE);
		snprintf(command, MAXLINE, "PASS %s\r\n", buf);
	}
	debug(command);
	Writen(sockfd, command, strlen(command));
}

int setServerConnMode(int sockfd) {

	char buf[MAXLINE];
	char activeMsg[MAXLINE];

	DATA_CONN_MODE = ON;

	if (ACTIVE_MODE == OFF) {
		debug("PASV\r\n");
		Writen(sockfd, "PASV\r\n", strlen("PASV\r\n"));
		return 1;
	} else if (ACTIVE_MODE == ON) {
		makeActiveMsg(getMyAddr(sockfd),activeMsg);
		//fprintf(stderr,"%s",activeMsg);
		debug(activeMsg);
		Writen(sockfd, activeMsg, strlen(activeMsg));
		return 2;
	}
	return -1;
}

int setServerBinaryMode(int sockfd) {
	debug("TYPE B\r\n");
	Writen(sockfd,"TYPE B\r\n",strlen("TYPE B\r\n"));
	return 1;

}

int setServerAsciiMode(int sockfd) {
	debug("TYPE A\r\n");
	Writen(sockfd,"TYPE A\r\n",strlen("TYPE A\r\n"));
	return 1;
}



